package com.chinackts.common.sharding;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Properties;

public class MonthShardingAlgorithm implements StandardShardingAlgorithm<Date> {

    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyyMM");

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        String suffix = FORMAT.format(shardingValue.getValue());
        for (String tableName : availableTargetNames) {
            if (tableName.endsWith(suffix)) {
                return tableName;
            }
        }
        throw new UnsupportedOperationException("No table found for suffix: " + suffix);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        return Collections.emptyList();
    }

    @Override
    public void init(Properties props) {}

    @Override
    public String getType() {
        return "MONTH_SHARDING";
    }

    @Override
    public Properties getProps() {
        return new Properties();
    }
}